<?php
include_once 'checkLogin.php';
$carID = $_POST['carID'];
$code = $_POST['code'];
if($code !== $_SESSION['code']){
    echo "<script>alert('验证码错误');location.href='showCode.php?carID=$carID';</script>";
    exit;
}
//第1步，更新carinfo表格
//第2步，在votedetail表格中添加记录
//开启mysql的事务机制，确保两个操作都正常实现
include_once 'conn.php';
mysqli_query($conn,'BEGIN');//这样操作后，mysql会自动关闭autocommit

//加入各种投票限制条件
//第3个限制。时间间隔至少15s
$sql = "select postttime from votedetail where userid = ".$_SESSION['loggedUserID'] ." order by id desc limit 0,1";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result)){
    //说明此人以前投过票，那就要查看最后投票的时间和现在的时间差是否大于15s
    $info = mysqli_fetch_array($result);
    if(time() - $info['postttime'] < 15){
        echo "<script>alert('两次投票至少需要间隔15s');window.top.location.href='index.php';</script>";
        exit;
    }
}
/*//第4个限制，同一天，同一个IP地址最多只能投15票
$sql = "select 1 from votedetail where ip = '".getIp()."' and FROM_UNIXTIME(postttime,'%Y-%m-%d') = '".date("Y-m-d")."'";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result)>15){
    echo "<script>alert('同一天，同一个IP地址最多可以投15票。');history.back();</script>";
    exit;
}*/
/*//第4个限制，黑名单中的IP地址无法投票（有效期内）
$sql = "select 1 from ipfilter where ip = '".getIp()."' and expires > unix_timestamp(current_timestamp())";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result)){
    echo "<script>alert('当前IP地址处于封禁期内，无法投票');history.back();</script>";
    exit;
}*/
//第4个限制，黑名单中的IP地址无法投票（有效期内，过期了则自动删除此IP）
$sql = "select id,expires from ipfilter where ip = '".getIp()."'";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result)){
    //说明此IP在黑名单里
    $info = mysqli_fetch_array($result);
    if($info['expires'] > time()){
        //说明此IP还在封禁期内
        echo "<script>alert('当前IP地址处于封禁期内，无法投票');window.top.location.href='index.php';</script>";
        exit;
    }
    else{
        //说明此IP虽然在黑名单里，但是已经解禁，则删除此IP
        $sql = "delete from ipfilter where id = ".$info['id'];
        $result = mysqli_query($conn,$sql);
    }
}
//第1个限制，每人每天只能给同一辆车最多投5票
$sql = "select 1 from votedetail where userid = ".$_SESSION['loggedUserID']." and carid = $carID and FROM_UNIXTIME(postttime,'%Y-%m-%d') = '".date("Y-m-d")."'";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) >= 5){
    //说明已经投过5票了，不能再投票
    echo "<script>alert('一人一天只能给一辆车投5票');window.top.location.href='index.php';</script>";
    exit;
}
//第2个限制，一人一天最多只能给3辆车投票
$sql = "SELECT carid FROM votedetail WHERE FROM_UNIXTIME( postttime, '%Y-%m-%d' ) = '".date("Y-m-d")."'  and userid = ".$_SESSION['loggedUserID']." and carid <> $carID GROUP BY carid";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) == 3){
    echo "<script>alert('一人一天只能给三辆车投票');window.top.location.href='index.php';</script>";
    exit;
}

//第1个操作
$sql1 = "update carinfo set carNum = carNum + 1 where id = $carID";
$result1 = mysqli_query($conn,$sql1);
/*echo mysqli_error($conn);
echo "<br>";*/
//第2个操作
$sql2 = "insert into votedetail (userid, carid, postttime,ip) VALUES ('".$_SESSION['loggedUserID']."','$carID','".time()."','".getIp()."')";
$result2 = mysqli_query($conn,$sql2);
/*echo mysqli_error($conn);
exit;*/
if($result1 && $result2){
    //说明两个操作都成功了，就可以提交修改了
    mysqli_query($conn,'COMMIT');
    echo "<script>alert('投票成功');window.top.location.href='index.php';</script>";
}
else{
    mysqli_query($conn,'ROLLBACK');
    echo "<script>alert('投票失败');window.top.location.href='index.php';</script>";
}
function getIp()
{
    if ($_SERVER["HTTP_CLIENT_IP"] && strcasecmp($_SERVER["HTTP_CLIENT_IP"], "unknown")) {
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    } else {
        if ($_SERVER["HTTP_X_FORWARDED_FOR"] && strcasecmp($_SERVER["HTTP_X_FORWARDED_FOR"], "unknown")) {
            $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        } else {
            if ($_SERVER["REMOTE_ADDR"] && strcasecmp($_SERVER["REMOTE_ADDR"], "unknown")) {
                $ip = $_SERVER["REMOTE_ADDR"];
            } else if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'],
                    "unknown")
            ) {
                $ip = $_SERVER['REMOTE_ADDR'];
            } else {
                $ip = "unknown";
            }
        }
    }
    return ($ip);
}
